﻿using MyMes.Dto;
using MyMes.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels.Repository;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using VOL.Entity.DomainModels;
using MyMES.IServices.ArrivalNotices;
using VOL.Core.Utilities.Response;
using VOL.Entity.DomainModels.Core;


namespace MyMES.Services.ArrivalNotices
{
    /// <summary>
    /// 到货通知单服务类，提供到货通知单相关的业务操作
    /// </summary>
    public class ArrivalNoticeService : IArrivalNoticeService
    {
        private readonly IBaseRepository<ArrivalNotice> _shipmentRepository;
        private readonly IBaseRepository<VOL.Entity.DomainModels.Supplier> _supplierRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="shipmentRepository">到货通知单仓储接口</param>
        /// <param name="supplierRepository">供应商仓储接口</param>
        public ArrivalNoticeService(IBaseRepository<ArrivalNotice> shipmentRepository, IBaseRepository<VOL.Entity.DomainModels.Supplier> supplierRepository)
        {
            _shipmentRepository = shipmentRepository;
            _supplierRepository = supplierRepository;
        }

        /// <summary>
        /// 创建到货通知单
        /// </summary>
        /// <param name="arrivalNotice">到货通知单实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> CreateShipmentsModel(ArrivalNotice arrivalNotice)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                await _shipmentRepository.AddAsync(arrivalNotice);
                return response.OK("新增到货通知单成功");
            }
            catch (Exception ex)
            {
                return response.Error($"新增到货通知单失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取到货通知单列表
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>分页后的到货通知单列表</returns>
        public async Task<PageGridData<ArrivalNoticeListDto>> GetShipmentsModelList(GetArrivalNoticeDto dto)
        {
            PageGridData<ArrivalNoticeListDto> pageData = new PageGridData<ArrivalNoticeListDto>();

            // 构建查询
            var query = from a in _shipmentRepository.GetAll()
                        join s in _supplierRepository.GetAll() on a.SupplierCode equals s.SupplierCode
                        select new ArrivalNoticeListDto
                        {
                            Id = a.Id,
                            NoticeCode = a.NoticeCode,
                            NoticeName = a.NoticeName,
                            PurchaseOrderCode = a.PurchaseOrderCode,
                            SupplierName = s.SupplierName,
                            ContactPerson = a.ContactPerson,
                            Phone = a.Phone,
                            DeliveryDate = a.DeliveryDate,
                            Status = a.DeliveryDate < DateTime.Now ? "已入库" : "待入库",
                            SupplierCode = s.SupplierCode,
                            Remark = a.Remark,
                        };

            // 使用WhereIf方法进行条件查询
            query = query.WhereIF(!string.IsNullOrEmpty(dto.NoticeCode),
                                 x => x.NoticeCode.Contains(dto.NoticeCode));

            query = query.WhereIF(!string.IsNullOrEmpty(dto.NoticeName),
                                 x => x.NoticeName.Contains(dto.NoticeName));

            query = query.WhereIF(!string.IsNullOrEmpty(dto.PurchaseOrderCode),
                                 x => x.PurchaseOrderCode.Contains(dto.PurchaseOrderCode));

            query = query.WhereIF(!string.IsNullOrEmpty(dto.SupplierCode),
                                 x => x.SupplierName.Contains(dto.SupplierCode));

            query = query.WhereIF(!string.IsNullOrEmpty(dto.ContactPerson),
                                 x => x.ContactPerson.Contains(dto.ContactPerson));

            query = query.WhereIF(!string.IsNullOrEmpty(dto.Phone),
                                 x => x.Phone.Contains(dto.Phone));

            // 日期查询 - 如果有日期查询条件，则查询当天
            if (dto.DeliveryDate.HasValue)
            {
                DateTime startDate = dto.DeliveryDate.Value.Date;
                DateTime endDate = startDate.AddDays(1).AddSeconds(-1);
                query = query.Where(a => a.DeliveryDate >= startDate && a.DeliveryDate <= endDate);
            }

            // 获取总记录数
            pageData.total = await query.CountAsync();

            // 分页处理
            var data = await query.OrderByDescending(a => a.DeliveryDate)
                                 .Skip((dto.PageIndex - 1) * dto.PageSize)
                                 .Take(dto.PageSize)
                                 .ToListAsync();

            pageData.rows = data;

            return pageData;
        }


        /// <summary>
        /// 批量删除到货通知单
        /// </summary>
        /// <param name="ids">到货通知单ID列表，以逗号分隔的字符串</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> DelShipments(string ids)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                if (string.IsNullOrEmpty(ids))
                {
                    return response.Error("未选择需要删除的记录");
                }

                // 将逗号分隔的字符串转换为整数ID列表
                List<int> idList = new List<int>();
                foreach (var id in ids.Split(','))
                {
                    if (int.TryParse(id.Trim(), out int parsedId))
                    {
                        idList.Add(parsedId);
                    }
                }

                if (idList.Count == 0)
                {
                    return response.Error("无效的ID格式");
                }
                // 执行批量删除
                await _shipmentRepository.DelAll(a => idList.Contains(a.Id));
                
                return response.OK($"删除成功");
            }
            catch (Exception ex)
            {
                return response.Error($"批量删除到货通知单失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 更新到货通知单
        /// </summary>
        /// <param name="arrivalNotice">到货通知单实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> UpdateShipmentsModel(ArrivalNotice arrivalNotice)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                await _shipmentRepository.UpdateAsync(arrivalNotice);
                return response.OK("更新到货通知单成功");
            }
            catch (Exception ex)
            {
                return response.Error($"更新到货通知单失败：{ex.Message}");
            }
        }
        
    }
}
